// 插件的配置及封装>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

const gulp = require("gulp");
const connect = require("gulp-connect");//服务器启动
const concat = require("gulp-concat");//合并js文件

var sass = require('gulp-sass');//将scss文件转换成css文件
sass.compiler = require('node-sass');//将scss文件转换成css文件
var uglify = require('gulp-uglify');//用于JS文件压缩
let cleanCSS = require('gulp-clean-css');//用于css文件压缩
const babel = require("gulp-babel");//ES6转ES5
const proxy = require('http-proxy-middleware')//解决跨域请求问题


// ======================================================================
// js文件的合并-------------start--------------
//获取src中scripts下无论层级的所有文件，并去除文件夹后将文件打包在dev中的scripts中。
function mergeMyScripts(json, prefix = 'scripts-', mode = 'dev'){
      let scriptsTaskArray = [];
      for(let attr in json){
            scriptsTaskArray.push(prefix + attr)
            if(mode === 'dev'){
                devScriptsMode(json, prefix, attr);
            }else if (mode === "build") {
                buildScriptsMode(json, prefix, attr)
            }
      }
      return scriptsTaskArray
}
// scripts 开发环境下配置
function devScriptsMode(json, prefix, attr){
    gulp.task(prefix + attr ,()=>{
        return gulp.src([json[attr].src + '*.+(js|jsx)'])
        .pipe(concat(attr + '.js'))
        .pipe(gulp.dest('./dev/scripts'))
        .pipe(connect.reload());
  })
}
// js文件的合并-------------end--------------

// scripts 构建环境下配置;
function buildScriptsMode(json, prefix, attr) {
    gulp.task(prefix + attr, () => {
        return gulp.src([json[attr].src + "*.+(js|jsx)"])
            .pipe(babel({
                presets: ['@babel/env']
            }))
            .pipe(concat(attr + ".js"))
            .pipe(uglify())
            .pipe(gulp.dest("./dist/scripts"))
    })
}

// 封装scripts的监听------------start----------------
function watchScripts(json , prefix){
      for(let attr in json){
            gulp.watch(json[attr].src + '*.js',[prefix + attr])
      }
}
// 封装scripts的监听------------end----------------
// ======================================================================


// ======================================================================
// scss文件的合并并转换成css-------------start--------------
function mergeMyScss(json, prefix = 'scss-', mode = 'dev'){
      let scssTaskArray = [];
      for(let attr in json){
            scssTaskArray.push(prefix + attr);
            if(mode === 'dev'){
                devScssMode(json, prefix, attr);
            }else if (mode === "build") {
                buildScssMode(json, prefix, attr)
            }
      }
      return scssTaskArray
}
// scss 开发配置
function devScssMode(json, prefix, attr){
    gulp.task(prefix + attr, () => {
        return gulp.src(json[attr].src + '*.+(scss|sass)')
        .pipe(concat(attr +'.scss'))
        // .pipe(concat('damaiindex.scss'))
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./dev/stylesheets'))
        .pipe(connect.reload());
    });
}
// scss文件的合并并转换成css-------------end--------------

// scss build配置
function buildScssMode(json, prefix, attr){
    gulp.task(prefix + attr, () => {
        return gulp.src(json[attr].src + '*.+(scss|sass)')
        .pipe(concat(attr + '.scss'))
        .pipe(sass())
        .pipe(cleanCSS({ debug: true }, (details) => {
            console.log(`${details.name}: ${details.stats.originalSize}`);
            console.log(`${details.name}: ${details.stats.minifiedSize}`);
        }))
        .pipe(gulp.dest('./dist/stylesheets'))
    });
}

// 封装scss的监听------------start----------------
function watchScss(json , prefix){
      for(let attr in json){
            gulp.watch(json[attr].src + '*.scss',[prefix + attr])
      }
}
// 封装scss的监听------------end----------------
// ======================================================================

function gpProxy(proxyList){
    let result = [];
    for(let attr in proxyList) {
          let options = {
                target : proxyList[attr].url,
                changeOrigin : true ,
                pathRewrite : !proxyList[attr].rewrite ? {
                      ["^"+attr] : ""
                } : {}
          };
          result.push( proxy( attr , options) )
    }
   return result;
}

module.exports = {
    mergeMyScripts,
    watchScripts,
    mergeMyScss,
    watchScss,
    gpProxy,
}